<template>
<BasicModal v-bind="$attrs" @register="registerModal" destroyOnClose :title="title" :width="800" @ok="handleSubmit">
    <BasicForm @register="registerForm" @eventFormModel="eventFormModel">
        <template #formFooter v-if="dataSource.length">
            <h2 style="font-size:16px">成本计算器</h2>
            <a-table style="width:100%" bordered :dataSource="dataSource" :columns="columnss" :pagination="false">
                <template #bodyCell="{ column, record }">
                  <template v-if="column.key === 'totalCost'">
                    {{ record.totalCost ? parseFloat(record.totalCost).toFixed(0) : 0 }}
                  </template>
                  <template v-if="column.key === 'totalAmount'">
                    {{ record.totalAmount ? parseFloat(record.totalAmount).toFixed(0) : 0 }}
                  </template>
                  <template v-if="column.key === 'remainderBudget'">
                    {{ record.remainderBudget ? parseFloat(record.remainderBudget).toFixed(0) : 0 }}
                  </template>
                  <template v-if="column.key === 'currentMonthConsume'">
                    {{ record.currentMonthConsume ? parseFloat(record.currentMonthConsume).toFixed(0) : 0 }}
                  </template>
    <!--                <template v-if="column.key === 'costStatus'">
                        <a-tag v-if="record.costStatus == 1" color="green">正常</a-tag>
                        <a-tag v-if="record.costStatus == 2" color="orange">接近阈值</a-tag>
                        <a-tag v-if="record.costStatus == 3" color="red">接近预警值</a-tag>
                    </template>-->
                    <template v-if="column.key ==='costPercent'">
                        {{ (record.costPercent * 100).toFixed(0) }}%
                    </template>
                </template>
            </a-table>
        </template>
    </BasicForm>
    <VerifyInfo :verifyType="6" ref="childRef"/>
</BasicModal>
</template>
<script lang="ts" setup>
    import {ref, computed, unref} from 'vue';
    import {BasicModal, useModalInner} from '/@/components/Modal';
    import VerifyInfo from './verifyInfo.vue'
    import {BasicForm, useForm} from '/@/components/Form/index';
    import {formSchema} from '../MonsterTripCostSubmit.data';
    import {saveOrUpdate} from '../MonsterTripCostSubmit.api';
    import {queryCurrentCostBudget} from '../MonsterSupplierCostSubmit.api';
    import { useMessage } from '/@/hooks/web/useMessage';
    import { countStatus, notEmpty } from '/@/utils/tool'
    // Emits声明
    const emit = defineEmits(['register','success']);
    const isUpdate = ref(true);
    const dataSource = ref<any>([])
    const dataOldSource = ref<any>('')
    const childRef = ref()
    let oId = ''
    const isType = ref('add')
    const columnss = ref([
    {
        title: '差旅总额',
        dataIndex: 'totalCost',
        key: 'totalCost',
    },
    {
        title: '已使用额度',
        dataIndex: 'totalAmount',
        key: 'totalAmount',
    },
    {
        title: '已使用百分比(%)',
        dataIndex: 'costPercent',
        key: 'costPercent',
    },
    {
        title: '当前剩余',
        dataIndex: 'remainderBudget',
        key: 'remainderBudget',
    },
    // {
    //     title: '当前预算状态',
    //     dataIndex: 'costStatus',
    //     key: 'costStatus',
    // },
])
    //表单配置
    const [registerForm, {setProps,resetFields, setFieldsValue, validate}] = useForm({
        //labelWidth: 150,
        schemas: formSchema,
        showActionButtonGroup: false,
        baseColProps: {span: 24}
    });
    //表单赋值
    const [registerModal, {setModalProps, closeModal}] = useModalInner(async (data) => {
        dataSource.value = []
        dataOldSource.value = ''
        oId = ''
        isType.value = data.isType
        //重置表单
        await resetFields();
        setModalProps({confirmLoading: false,showCancelBtn:!!data?.showFooter,showOkBtn:!!data?.showFooter});
        isUpdate.value = !!data?.isUpdate;
        if (unref(isUpdate)) {
            childRef.value.childMethod(data.record)
            oId = data.record.projectId
            await list(data.record)
            //表单赋值
            await setFieldsValue({
                ...data.record,
            })
        }else {
            childRef.value.childMethod()
        }
        // 隐藏底部时禁用整个表单
        setProps({ disabled: !data?.showFooter })
    });
    //设置标题
    const title = computed(() => (!unref(isUpdate) ? '新增' : '编辑'));
    //表单提交事件
    async function handleSubmit(v) {
        try {
            let values = await validate();
            const { createMessage } = useMessage()
            if(!notEmpty(values, ['projectId', 'totalTripAmount','type'])) {
                return createMessage.warn('请完善信息')
            }
            if( dataSource.value[0].remainderBudget <0) {
                return createMessage.warn('申请额度超出预算，无法提交')
            }
            let f = values.uploadFile ? JSON.parse(values.uploadFile) : []
            if(!f.length) {
            return createMessage.warn('请上传附件');
            }
            let file:any = []
            f.forEach((url) => {
                file.push({
                    annexName: url.fileName,
                    annexType: url.fileType,
                    url: url.filePath,
                })
            })
            values.uploadFile = f.length ? JSON.stringify(file) : ''
            setModalProps({confirmLoading: true});
            //提交表单
            await saveOrUpdate(Object.assign(values,{annex:JSON.stringify(file),status:1}), isUpdate.value);
            //关闭弹窗
            closeModal();
            //刷新列表
            emit('success');
        } finally {
            setModalProps({confirmLoading: false});
        }
    }

    async function list (item) {
        let res = await queryCurrentCostBudget({operateType:2, submitType:3,projectId:item.projectId,payAmount: item.totalTripAmount ? item.totalTripAmount : 0})//.then(res => {
            dataSource.value = [res]
            dataOldSource.value = JSON.stringify(res)
            dataSource.value[0].payAmount = item.totalTripAmount ? item.totalTripAmount : 0
        // })
    }

    function eventFormModel (e) {
        if(isType.value =='info') {
            setTimeout(() => {
                isType.value = 'add'
            },1000)
            return
        }
        if(e && e.projectId && oId != e.projectId) {
            oId = e.projectId
            list(e)
        }
        if(e.totalTripAmount && dataSource.value.length) {
           dataSource.value[0].totalAmount = 0;
            // countStatus(1,dataSource.value,dataOldSource.value,e.totalTripAmount)
            // let cost = (Number(dataSource.value[0].currentAvablieCost) - (Number(dataSource.value[0].currentMonthConsume) + Number(e.totalTripAmount))) / Number(dataSource.value[0].currentAvablieCost)
            // console.log('cost', cost)
            // if(cost < dataSource.value[0].remindThreshold && cost > dataSource.value[0].warningThreshold) {
            //     dataSource.value[0].costStatus = 2
            // }
            // else if(cost < dataSource.value[0].warningThreshold) {
            //     dataSource.value[0].costStatus = 3
            // }
            // else {
            //     dataSource.value[0].costStatus = 1
            // }
            // 、输入金额时当前剩余remainderBudget = remainderBudget - e.Amount(输入金额)
            let old = JSON.parse(dataOldSource.value)
            dataSource.value[0].remainderBudget = Number(old.remainderBudget) - Number(e.totalTripAmount)

            dataSource.value[0].totalAmount =   Number(old.totalAmount)  + Number(e.totalTripAmount)
            // dataSource.value[0].payAmount = e.totalTripAmount
            dataSource.value[0].costPercent = (Number(old.totalAmount) + Number(e.totalTripAmount)) / Number(dataSource.value[0].totalCost)

            console.log('Number(dataSource.value[0].totalAmount',Number(dataSource.value[0].totalAmount));
            console.log('Number(e.totalTripAmount)',Number(e.totalTripAmount));
            console.log('totalCost',Number(dataSource.value[0].totalCost));
        }
        if(!e.totalTripAmount && dataSource.value.length) {
            let old = JSON.parse(dataOldSource.value)
            // dataSource.value[0].payAmount = ''
            dataSource.value[0].remainderBudget = old.remainderBudget
            dataSource.value[0].costPercent = old.costPercent
        }
    }
</script>

<style lang="less" scoped>
    /** 时间和数字输入框样式 */
:deep(.ant-input-number){
        width: 100%
    }

    :deep(.ant-calendar-picker){
        width: 100%
    }
</style>
